import random
import string
import io
import uuid
import time
import os
from PIL import Image, ImageDraw, ImageFont, ImageFilter
from fastapi import APIRouter, Response
from starlette.requests import Request

router = APIRouter()


def generate_captcha_text(length=4):
    """生成验证码文字"""
    return ''.join(random.choices(string.ascii_uppercase + string.digits, k=length))


def generate_captcha_image(text, width=120, height=40):
    """生成验证码图片"""
    image = Image.new("RGB", (width, height), (255, 255, 255))
    # font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", 28)
    font = ImageFont.truetype("arial.ttf", 28)
    draw = ImageDraw.Draw(image)

    # 绘制文字
    for i, ch in enumerate(text):
        draw.text(
            (10 + i * 25, 5),
            ch,
            font=font,
            fill=(random.randint(0, 150), random.randint(0, 150), random.randint(0, 150))
        )

    # 添加干扰点
    for _ in range(100):
        draw.point(
            (random.randint(0, width - 1), random.randint(0, height - 1)),
            fill=(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))
        )

    # 模糊
    image = image.filter(ImageFilter.BLUR)
    return image


@router.get("/captcha")
async def get_captcha(request: Request):
    """生成验证码并存入 session"""
    text = generate_captcha_text()
    image = generate_captcha_image(text)

    # 确保 session_id 存在
    session_id = request.session.get("session_id")
    if not session_id:
        session_id = str(uuid.uuid4())
        request.session["session_id"] = session_id

    # 保存验证码（过期时间 2 分钟）
    now = int(time.time())
    request.session["captcha"] = {"code": text, "expires": now + 120}

    # Debug 打印
    print("PID:", os.getpid(), "存储验证码:", text, "session_id:", session_id, "session 数据:", request.session["captcha"])

    # 输出图片
    buf = io.BytesIO()
    image.save(buf, "PNG")
    buf.seek(0)
    return Response(content=buf.getvalue(), media_type="image/png")


def verify_captcha(request: Request, user_input: str) -> bool:
    """校验验证码"""
    data = request.session.get("captcha")
    print("PID:", os.getpid(), "验证 user_input:", user_input, "session 数据:", data)

    if not data:
        return False
    if int(time.time()) > data["expires"]:
        return False
    return data["code"].lower() == user_input.lower()
